/*
 * @Date         : 2022-07-21 19:35:14
 * @LastEditors  : zu1662
 * @LastEditTime : 2024-05-24 15:00:04
 * @Description  : 腾讯云OSS
 *
 * Copyright © 2022 by zu1662, All Rights Reserved.
 */
import OSS from 'cos-nodejs-sdk-v5';
import { OssClient } from '../oss.client';
import { OssInfo } from '../oss.interface';

export class TencentOssClient extends OssClient {
  bucket: string;
  constructor(config: OssInfo) {
    super(config);
    this.ossClient = new OSS({
      SecretId: this.config.ossAccessId,
      SecretKey: this.config.ossAccessSecret,
    });
  }

  async putFile(filename: string, buffer: ReadableStream<any>, options?: any): Promise<string> {
    const result = await this.ossClient.putObject({
      Bucket: this.config.ossBucket,
      Region: this.config.ossRegion,
      Key: filename,
      Body: buffer,
      ...options,
    });

    return 'https://' + result.Location;
  }

  async deleteFile(filename: string): Promise<boolean> {
    try {
      await this.ossClient.deleteObject({
        Bucket: this.config.ossBucket,
        Region: this.config.ossRegion,
        Key: filename,
      });
      return true;
    } catch (e) {
      return false;
    }
  }

  async deleteFiles(filenames: string[]): Promise<boolean> {
    try {
      await this.ossClient.deleteMultipleObject({
        Bucket: this.config.ossBucket,
        Region: this.config.ossRegion,
        Objects: filenames.map(file => ({ Key: file })),
      });
      return true;
    } catch (e) {
      return false;
    }
  }
}
